const cardCls = 'card'
const cardOpenCls = composeClsName(cardCls, 'open')
const pageCls = 'flip-card__container'
const activePageCls = composeClsName(pageCls, 'active')
const flippedPageCls = composeClsName(pageCls, 'flipped')

document.onclick = event => {
    console.log('event: ', event);
    var cardDom = event.path.filter(ele => [cardOpenCls, cardCls].includes(ele?.className))?.[0]
    if (cardDom) {
        var pageActiveDom = event.path.filter(ele => ele?.className?.includes(activePageCls))?.[0]
        var pageFlipedDom = event.path.filter(ele => ele?.className?.includes(flippedPageCls))?.[0]
        if (pageActiveDom) {
            cardDom.className = cardOpenCls
            pageActiveDom.className = flippedPageCls
            if (pageActiveDom.nextElementSibling) pageActiveDom.nextElementSibling.className = activePageCls
        } else if (pageFlipedDom) {
            pageFlipedDom.className = activePageCls
            if (pageFlipedDom.nextElementSibling) pageFlipedDom.nextElementSibling.className = pageCls
            if (!pageFlipedDom.previousElementSibling) cardDom.className = cardCls
        }
    } else {
        const cardSectionDomList = document.querySelectorAll('.card-section')
        cardSectionDomList.forEach(section => {
            for (var index = 0; index < section.children.length; index++) {
                console.log('cardSectionDom[index].className: ', section.children[index].className);
                section.children[index].className = cardCls
            }
        })
        closeBook({ children: cardSectionDomList })
    }
}

function closeBook($dom) {
    for (var index = 0; index < $dom.children.length; index++) {
        if ($dom.children[index].className.includes(pageCls)) {
            $dom.children[index].className = index === 0 ? activePageCls : pageCls
        } else if ($dom.children[index]?.children) {
            closeBook($dom.children[index])
        }
    }
}

function composeClsName(...cls) {
    return cls?.join(' ') ?? ''
}